package com.sa.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author Architecture Station
 * @version 1.0
 * @website 
 */
@Component
@Slf4j
public class GrayReleaseGlobalFilter implements GlobalFilter, Ordered {

    private static final double GRAY_PROBABILITY = 0.1; // 10% 概率

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 10% 的概率引导到灰度服务
        if (ThreadLocalRandom.current().nextDouble() < GRAY_PROBABILITY) {
            // 修改 URI 指向灰度版本
            URI grayUri = URI.create("http://gray-service");
            exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR, grayUri);

            // 修改请求头中的 Host，以便服务发现正确工作
            ServerHttpRequest request = exchange.getRequest().mutate()
                    .header("Host", "gray-service")
                    .build();
            exchange = exchange.mutate().request(request).build();

            log.info("Request {} is routed to gray service {}", exchange.getRequest().getURI(), grayUri);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
